import { CustomProcessForm } from './types'
import { ref } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import { useFindTemplateById, useUpdateTemplateById } from './useTemplateList'

const { template, findTemplate } = useFindTemplateById()

const commanderList = [
  {
    id: uuidv4(),
    name: '张三',
  },
  {
    id: uuidv4(),
    name: '李四',
  },
  {
    id: uuidv4(),
    name: '王五',
  },
  {
    id: uuidv4(),
    name: '赵六',
  },
  {
    id: uuidv4(),
    name: '陈七',
  },
]

const sleep = (timestamp: number) => {
  return new Promise((resolve) => setTimeout(resolve, timestamp))
}

export const useFindCustomPorcess = () => {
  const findProcessListLoading = ref(false)
  const processList = ref<Array<CustomProcessForm>>([])

  const findPorcessList = async (templateId: string) => {
    findProcessListLoading.value = true
    await findTemplate(templateId)
    findProcessListLoading.value = false
    processList.value = template.value.processList
  }

  return {
    processList,
    findProcessListLoading,
    findPorcessList,
  }
}

export const useCustomProcessForm = () => {
  const formSaveLoading = ref(false)
  const form = ref<CustomProcessForm>({
    id: '',
    nodes: [],
  })

  const resetForm = () => {
    form.value = {
      id: '',
      nodes: [],
    }
  }

  const formSave = async () => {
    formSaveLoading.value = true
    await sleep(2000)
    const processIndex = template.value.processList.findIndex((item) => item.id === form.value.id)
    if (processIndex >= 0) {
      template.value.processList[processIndex] = form.value
    } else {
      form.value.id = uuidv4()
      template.value.processList.push(form.value)
    }
    useUpdateTemplateById(template.value)
    formSaveLoading.value = false
  }

  return {
    form,
    formSaveLoading,
    formSave,
    resetForm,
  }
}

export const useGetNodeCommanderList = () => {
  const getNodeCommanderListLoading = ref(false)
  const nodeCommanderList = ref<Array<{ id: string; name: string }>>([])

  const getNodeCommanderList = async () => {
    getNodeCommanderListLoading.value = true
    await sleep(2000)
    nodeCommanderList.value = commanderList
    getNodeCommanderListLoading.value = false
  }

  return {
    nodeCommanderList,
    getNodeCommanderListLoading,
    getNodeCommanderList,
  }
}
